package com.wf.javase;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author mpk
 * @since 2024/6/22 15:24:23
 */
public class CPTest {

    public static void main(String[] args) {

        LinkedBlockingDeque<String> strings = new LinkedBlockingDeque<>(5);

        Thread c = new Thread(new Consumer(strings), "消费者");
        Thread p = new Thread(new Product(strings), "生产者");

        c.start();
        p.start();

    }

}

class Consumer implements Runnable {

    private LinkedBlockingDeque<String> strings;

    public Consumer(LinkedBlockingDeque<String> strings) {
        this.strings = strings;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1500);
                strings.take();
                System.out.println("消费者消费了一件物品"+"共有物品数量"+strings.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

class Product implements Runnable {

    private LinkedBlockingDeque<String> strings;

    public Product(LinkedBlockingDeque<String> strings) {
        this.strings = strings;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                strings.put("物品");
                System.out.println("生产者生产了一件物品"+"共有物品数量"+strings.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}